import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo {

    private ServerSocket serverSocket = null;

    public Demo(int p) throws IOException {
        serverSocket = new ServerSocket(p);
    }

    public void start() throws IOException {
        System.out.println("服务器上线");

        ExecutorService executorService = Executors.newCachedThreadPool();

        while (true) {
            Socket socket = serverSocket.accept();

            executorService.submit(() -> {
                poccess(socket);

            });
        }


    }

    private void poccess(Socket socket) {

        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner sc = new Scanner(inputStream);
            PrintWriter p = new PrintWriter(outputStream);


            while (true) {

                if (!sc.hasNext()) {
                    System.out.printf("[%s:%d] 客户端下线\n",socket.getInetAddress(),socket.getPort());
                    break;
                }
                String s1 = sc.next();
                String s2 = respond(s1);

                p.println(s2);

                p.flush();

                System.out.printf("[%s:%d] req:%s  resp:%s\n",socket.getInetAddress(),socket.getPort(),s1,s2);

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

    private String respond(String s1) {
        return s1;
    }

    public static void main(String[] args) throws IOException {


        Demo d = new Demo(9099);
        d.start();
    }

}
